//
//  CCAPIManager.swift
//  CCFoundation_Swift
//
//  Created by zjh on 2021/10/15.
//

import UIKit
import Alamofire

public class CCAPIManager {
    static var hostUrl = ""
    public class func Post(url: String,para: Parameters, headers: HTTPHeaders)->DataRequest{
        let jsonData = try? JSONSerialization.data(withJSONObject: para, options: [])
        var request = URLRequest(url: URL(string: hostUrl + url)!)
        request.httpMethod = HTTPMethod.post.rawValue
        request.headers = headers
        request.httpBody = jsonData
        AF.session.configuration.timeoutIntervalForRequest = 8
        debugPrint("请求地址：\(hostUrl)\(url)")
        return AF.request(request)
    }
    
    public class func Get(url: String,para: Parameters, headers: HTTPHeaders)->DataRequest{
        AF.session.configuration.timeoutIntervalForRequest = 8
        debugPrint("请求地址：\(hostUrl)\(url)")
        return AF.request(hostUrl + url, method: .get, parameters: para, headers: headers)
    }
}

// MARK: - 数据转换
/// 字典转模型
public func swift_dicToModel<T>(_ type: T.Type, value: Any?) -> T? where T: Decodable {
    guard let value = value else { return nil }
    return swift_dicToModel(type, value: value)
}

/// 字典转模型
public func swift_dicToModel<T>(_ type: T.Type, value: Any) -> T? where T : Decodable {
    guard let data = try? JSONSerialization.data(withJSONObject: value) else { return nil }
    let decoder = JSONDecoder()
    decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+Infinity", negativeInfinity: "-Infinity", nan: "NaN")
    return try? decoder.decode(type, from: data)
}
